package com.wispx.gateway.config.util;

import cn.hutool.json.JSONUtil;
import com.wispx.gateway.config.pojo.RouteDefinition;

import java.util.Collection;
import java.util.Objects;

import static com.wispx.gateway.common.constant.FilterConstant.GRAY_FILTER_NAME;
import static com.wispx.gateway.common.constant.FilterConstant.LOAD_BALANCE_FILTER_NAME;

public class FilterConfigUtil {

    private FilterConfigUtil() {

    }

    /**
     * 根据名字查找 filterConfig
     *
     * @param filterConfigs 从这个集合中查找FilterConfig
     * @param filterName    要查找的过滤器名字
     */
    public static RouteDefinition.FilterConfig findFilterConfigByName(Collection<RouteDefinition.FilterConfig> filterConfigs, String filterName) {
        if (filterConfigs == null || filterName == null || filterConfigs.isEmpty() || filterName.isEmpty()) {
            return null;
        }
        for (RouteDefinition.FilterConfig filterConfig : filterConfigs) {
            if (filterConfig == null) continue;
            if (Objects.equals(filterConfig.getName(), filterName)) {
                return filterConfig;
            }
        }
        return null;
    }

    /**
     * 将基础的FilterConfig转化为 FlowFilterConfig、GrayFilterConfig 等
     */
    public static <T> T findFilterConfigByClass(Collection<RouteDefinition.FilterConfig> filterConfigs, String filterName, Class<T> clazz) {
        RouteDefinition.FilterConfig filterConfig = findFilterConfigByName(filterConfigs, filterName);
        if (filterConfig == null) {
            return null;
        }
        return JSONUtil.toBean(filterConfig.getConfig(), clazz);
    }

    /**
     * 构建默认灰度过滤器Config
     */
    public static RouteDefinition.FilterConfig buildDefaultGrayFilterConfig() {
        RouteDefinition.FilterConfig filterConfig = new RouteDefinition.FilterConfig();
        filterConfig.setEnable(true);
        filterConfig.setName(GRAY_FILTER_NAME);
        filterConfig.setConfig(JSONUtil.toJsonStr(new RouteDefinition.GaryFilterConfig()));
        return filterConfig;
    }

    /**
     * 构建默认负载均衡过滤器Config
     */
    public static RouteDefinition.FilterConfig buildDefaultLoadBalanceFilterConfig() {
        RouteDefinition.FilterConfig filterConfig = new RouteDefinition.FilterConfig();
        filterConfig.setEnable(true);
        filterConfig.setName(LOAD_BALANCE_FILTER_NAME);
        filterConfig.setConfig(JSONUtil.toJsonStr(new RouteDefinition.LoadBalanceFilterConfig()));
        return filterConfig;
    }

}
